// backend/services/llmService.js
const axios = require('axios');
const config = require('../config');

/**
 * 接收完整的Prompt并调用API
 * @param {string} finalPrompt - 由前端构建好的，包含所有指令的最终Prompt
 * @param {string} apiKey - 大模型的API Key
 */
async function generateText(finalPrompt, apiKey) {
  try {
    const response = await axios.post(
      config.llm.apiUrl,
      {
        model: config.llm.defaultModel,
        messages: [{ role: 'user', content: finalPrompt }],
        max_tokens: 4096, 
      },
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
        },
      }
    );
    return response.data.choices[0].message.content;
  } catch (error) {
    logger.error('LLM API Error:', { 
        message: error.message, 
        data: error.response ? error.response.data : 'No response data' 
    });
    throw new Error('调用大模型API生成文本失败。');
  }
}

module.exports = { generateText };